package io.mft.plugin.tester;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.json.JSONUtil;
import io.mft.commons.config.ConfigProvider;
import io.mft.commons.function.RequestValue;
import io.mft.plugin.PAFunction;
import io.mft.plugin.PluginContext;
import io.mft.plugin.PluginFunction;
import io.mft.plugin.PluginInvoker;
import io.mft.plugin.PluginRequest;
import io.mft.plugin.PluginResponse;
import junit.framework.TestCase;

public class PluginFunctionTester<C extends PluginFunction<T>,T> extends TestCase {
	Logger logger = LoggerFactory.getLogger(getClass());

	public void addField(String key, String value) {
		request.getRequestValue().set(key, value);
	}
	public void addField(String key, Object value) {
		request.getRequestValue().set(key, value);
	}
	public void addFields(Map<String, String> map) {
		request.getRequestValue().putAll(map);
	}

	public interface InitingHandler{
		void handle();
	}
	final PluginRequest request;
	final Class<C> function;
	final PluginContext<T> context;
	public PluginFunctionTester(Class<C> function, T contextValue,InitingHandler ...handlers) throws Exception{
		for (InitingHandler initingHandler : handlers) {
			initingHandler.handle();
		}
		this.function = function;
		request = new PluginRequest(new RequestValue());
		PluginResponse response=new PluginResponse();
		context = new PluginContext<T>(request, contextValue,response);
	}
	public PluginContext<T> getContext() {
		return context;
	}
	public T getContextValue() {
		return context.getValue();
	}
	public void testInvoke() {
		try {
			logger.info("请求入参:{}", context.getRequest().getRequestValue());
			PAFunction paFunction=function.getDeclaredAnnotation(PAFunction.class);
			PluginResponse response=PluginInvoker.invoke(paFunction.value(), request.getRequestValue());
					//instance.doExecute(context);
			logger.info("请求响应:{}",response);
			context.getResponse().getDsName().forEach(r->{
				logger.info("请求响应->>>结果集KEY:{}->>>数据:{}", r.getName(),JSONUtil.toJsonStr(context.getResponse().listObject(r.getName())));
			});
		} catch (Throwable e) {
			logger.error("", e);
		}

	}
}
